package com.sh.learn.ibeifeng.webservice.axis;

import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.security.AuthenticatedUser;
import org.apache.axis.security.SecurityProvider;
import org.apache.axis.security.simple.SimpleSecurityProvider;

/**
 * web-inf/users.lst 下添加用户
 * server-config.wsdd 添加服务配置
 */
//sun sunhong

//<service name="AuthenticationService" provider="java:RPC">
//<parameter name="className" value="com.sh.learn.ibeifeng.webservice.axis.AuthenticationService" />
//<parameter name="allowedMethods" value="*" />
//<parameter name="allowedRoles" value="sun" />
//<requestFlow>
//  <handler name="authen" type="java:com.sh.learn.ibeifeng.webservice.axis.AuthenticationHandler" />
//</requestFlow>
//</service>
public class AuthenticationHandler extends BasicHandler{

	// 定义认证的参数
	String securityProvider = "securityProvider"; //安全级别对象
	String authenticatedUser = "authenticatedUser"; // 认证
	String unauthenticated = "unauthenticated"; // 未认证
	String canAuth = "canAuth"; //
	
    public void invoke(MessageContext msgContext) throws AxisFault {
		// 获取当前的安全服务对象
	    SecurityProvider provider = (SecurityProvider)msgContext.getProperty(securityProvider);
	    // 判断当前的安全机制状态
	    if(provider == null){
	    	// 创建安全服务对象
	    	provider = new SimpleSecurityProvider();
	    	// 设置到当前的ws服务中
	    	msgContext.setProperty(securityProvider, provider);
	    }
	    // 获取当前ws服务的认证信息
	    String id = msgContext.getUsername();
	    String pwd = msgContext.getPassword();
	    System.out.println(id + " " + pwd);
	    // 对访问的用户进行认证
	    AuthenticatedUser authUser = provider.authenticate(msgContext);
	    if(authUser == null){
	    	throw new AxisFault(unauthenticated, "authenticated error", null, null);
	    }
	    // 用户通过认证，将设置为认证用户
	    msgContext.setProperty(authenticatedUser, authUser);
    }
	
}
